﻿using System;
using CCE = CodeCamp.Model;
using SSP = System.Security.Principal;

namespace CodeCamp.Controllers
{
  public static class EventsHelper
  {

    public static int GetEventId(CodeCampDataRepository repository, string eventName, string defaultEventName)
    {
        return GetEventId(repository, eventName, defaultEventName, true);
    }
      
    public static int GetEventId(CodeCampDataRepository repository, string eventName, string defaultEventName, bool publicOnly)
    {
        var event_ = GetEvent(repository, eventName, defaultEventName, publicOnly);
        if (event_ == null)
            throw new Exception("Event not found");

        return event_.Id;
    }

    public static CCE.Event GetEvent(CodeCampDataRepository repository, string eventName, string defaultEventName)
    {
        return GetEvent(repository, eventName, defaultEventName, true);
    }

    public static CCE.Event GetEvent(CodeCampDataRepository repository, string eventName, string defaultEventName, bool publicOnly)
    {
        CCE.Event event_ = null;

        if (!string.IsNullOrWhiteSpace(eventName))
            event_ = repository.GetEvent(eventName, publicOnly);

        if (event_ == null)
            event_ = repository.GetEvent(defaultEventName, false);

        if (event_ == null)
            throw new Exception(string.Format("Neither event \"{0}\" nore event \"{1}\" was found.", eventName, defaultEventName));

        return event_;
    }

    public static CCE.Event GetEvent(CodeCampDataRepository repository, string eventName, string defaultEventName, SSP.IPrincipal principal)
    {
        CCE.Event event_ = null;

        if ((principal != null) && (principal.Identity != null) && (principal.Identity.IsAuthenticated))
        {
            if (!string.IsNullOrWhiteSpace(eventName))
                event_ = repository.GetEvent(eventName, false);

            if ((event_ != null) && !event_.EventIsPublic)
            {
                if (!principal.IsInRole(CodeCamp.Models.Shared.CCRoles.RoleNames.BigCheeze)
                    && (string.IsNullOrWhiteSpace(event_.NonPublicEventPreviewRole) || !principal.IsInRole(event_.NonPublicEventPreviewRole)))
                {
                    event_ = null;
                }
            }
        }
        if (event_ == null)
        {
            event_ = GetEvent(repository, eventName, defaultEventName, true);
        }

        return event_;
    }

    public static int GetEventId(CodeCampDataRepository repository, string eventName, string defaultEventName, SSP.IPrincipal principal)
    {
        CCE.Event event_ = GetEvent(repository, eventName, defaultEventName, principal);
        if (event_ != null)
            return event_.Id;
        return 0;
    }

  }
}